package cn.xiangyuanpin.web;

import cn.xiangyuanpin.pojo.Book;
import cn.xiangyuanpin.pojo.Cart;
import cn.xiangyuanpin.pojo.CartItem;
import cn.xiangyuanpin.service.BookService;
import cn.xiangyuanpin.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CartServlet extends  BaseServlet{
   private BookService bookService=new BookServiceImpl();

  protected  void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     int id=Integer.parseInt(req.getParameter("id"));
      Book book =    bookService.queryBookById(id);
      CartItem cartItem=new CartItem(book.getId(),book.getName(),1,book.getPrice(),book.getPrice());
      Cart cart=(Cart) req.getSession().getAttribute("cart");
      if(cart==null) {
          cart = new Cart();
          req.getSession().setAttribute("cart", cart);
      }
      System.out.println(cartItem);
      cart.addItem(cartItem);
      System.out.println(cart);
    resp.sendRedirect(req.getContextPath());
  }


    protected  void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart=(Cart) req.getSession().getAttribute("cart");
        if(cart!=null){
            cart.clear();
            req.getRequestDispatcher("pages/cart/cart.jsp").forward(req,resp);
        }
    }



}
